package model.webService;

import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.SocketException;

import android.util.Log;

/**
 * Handles calls sent to the web service.
 */
public class CallSender 
{
	private final static String TAG = CallSender.class.getSimpleName();
	
	//Serial of a device is unique
	private static final String machineName = android.os.Build.SERIAL;
	
	/**
	 * Sends a call to the web service.
	 * @param socket The socket to which to connect.
	 * @param msg The message to send along with the call.
	 * @param command The command to indicate the purpose of the call.
	 */
	public static void sendSocketCall(Socket socket, String msg, Command command) throws SocketException
	{
		try 
		{
			if(socket != null)
			{
				BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8"));
				
				//get the integer value of the enum
				int cmd = command.ordinal();
				String message = String.format("%d,%s,%s|", cmd, machineName, msg);
				
				Log.i(TAG, String.format("sending message: \"%s\"", message));
		        
				writer.write(message);
				writer.flush();
			}
		}
		catch (Exception e) 
		{
			Log.e(TAG, e.toString());
		}
	}
	
	/**
	 * Sends a call to the web service without a message.
	 * @param socket The socket to which to connect.
	 * @param command The command to indicate the purpose of the call.
	 */
	public static void sendSocketCall(Socket socket, Command command) throws SocketException
	{
		sendSocketCall(socket, "", command);
	}
	
}
